import { ref, computed } from 'vue'

const AUTH_KEY = 'auth_verified'
const AUTH_TIMESTAMP_KEY = 'auth_timestamp'
const AUTH_EXPIRY_HOURS = 24 // 授权有效期24小时

const isAuthenticated = ref(false)

// 检查授权状态
const checkAuthStatus = () => {
  const authStatus = localStorage.getItem(AUTH_KEY)
  const authTimestamp = localStorage.getItem(AUTH_TIMESTAMP_KEY)
  
  if (!authStatus || !authTimestamp) {
    isAuthenticated.value = false
    return false
  }
  
  // 检查是否过期
  const timestamp = parseInt(authTimestamp)
  const now = Date.now()
  const expiry = AUTH_EXPIRY_HOURS * 60 * 60 * 1000 // 转换为毫秒
  
  if (now - timestamp > expiry) {
    // 授权已过期，清除本地存储
    clearAuth()
    isAuthenticated.value = false
    return false
  }
  
  isAuthenticated.value = authStatus === 'true'
  return isAuthenticated.value
}

// 设置授权状态
const setAuthenticated = () => {
  isAuthenticated.value = true
  localStorage.setItem(AUTH_KEY, 'true')
  localStorage.setItem(AUTH_TIMESTAMP_KEY, Date.now().toString())
}

// 清除授权状态
const clearAuth = () => {
  isAuthenticated.value = false
  localStorage.removeItem(AUTH_KEY)
  localStorage.removeItem(AUTH_TIMESTAMP_KEY)
}

// 登出
const logout = () => {
  clearAuth()
}

export const useAuth = () => {
  // 初始化时检查授权状态
  if (!isAuthenticated.value) {
    checkAuthStatus()
  }
  
  return {
    isAuthenticated: computed(() => isAuthenticated.value),
    setAuthenticated,
    clearAuth,
    logout,
    checkAuthStatus
  }
}